package com.jvm;

import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;

public class PhantomReferenceTest {

    private static PhantomReferenceTest obj;

    static ReferenceQueue referenceQueue = new ReferenceQueue();

    @Override
    protected void finalize() throws Throwable {
        System.out.println("调用finalize方法-- 准备复活对象");
        obj = this;
    }

    public static void main(String[] args) throws InterruptedException {

        Thread testQueue = new testQueue();
        testQueue.start();

        obj = new PhantomReferenceTest();
        PhantomReference<PhantomReferenceTest> phantomReference = new PhantomReference<>(obj, referenceQueue);

        System.out.println(phantomReference.get());

        obj = null;
        System.gc();
        Thread.sleep(1000);
        if (obj == null) {
//            System.out.println("对象复活了");
        } else {
            System.out.println("对象复活了");
        }

        obj = null;
        System.gc();
        Thread.sleep(1000);
    }

    private static class testQueue extends Thread {
        @Override
        public void run() {
            while (true) {
                try {
                    Reference remove = referenceQueue.remove();
                    if (remove != null) {
                        System.out.println("垃圾对象回收了啊");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
